<template>
  <div class="upload-body">
    <el-dialog
      v-model="centerDialogVisible"
      title="创建圈子"
      width="30%"
      center
      @close="close"
    >
      <!-- 表单 -->
      <el-form
        label-position="top"
        :model="formData"
        class="form-box"
        ref="formRef"
        :rules="formRules"
      >
        <el-form-item label="圈子头像" prop="head_portrait">
          <upload
            :multiple="false"
           
            @sucess="avatarUploadSucess"
            @fileQueued="avatarUploadFileQueued"
            v-show="!avatarUploadLoading"
            :maxSize="5"
          >
            <div class="avatar-upload-box f-d-c f-j-a-c" v-if="!formData.head_portrait">
              <svg-icon name="langshangchuang" class="upload-icon"></svg-icon>
              <span>上传图片</span>
              <span class="upload-title">建议尺寸120*120px</span>
            </div>

            <img
              class="avatar-img"
              v-if="formData.head_portrait"
              :src="formData.head_portrait"
              alt=""
            />
          </upload>
          <div
            v-if="avatarUploadLoading"
            class="avatar-upload-loading f-j-a-c"
            v-loading="avatarUploadLoading"
            element-loading-background="rgba(243,244,245,0.5)"
          >
            <img
              class="avatar-img"
              v-if="formData.head_portrait"
              :src="formData.head_portrait"
              alt=""
            />
          </div>
        </el-form-item>

        <el-form-item label="圈子背景图" prop="background_maps">
          <upload
            style="width: 100%"
            :multiple="false"
            :maxSize="5"
            @sucess="bannerUploadSucess"
            @fileQueued="bannerUploadFileQueued"
            v-show="!bannerUploadLoading"
          >
            <div
              class="avatar-upload-box banner-upload-box f-d-c f-j-a-c"
              v-if="!formData.background_maps"
            >
              <svg-icon name="langshangchuang" class="upload-icon"></svg-icon>
              <span>上传图片</span>
              <span class="upload-title">建议上传尺寸1300*300px,图片大小不超过1MB</span>
            </div>

            <img
              class="banner-img"
              v-if="formData.background_maps"
              :src="formData.background_maps"
              alt=""
            />
          </upload>
          <div
            v-if="bannerUploadLoading"
            class="avatar-upload-loading banner-upload-loading f-j-a-c"
            v-loading="bannerUploadLoading"
            element-loading-background="rgba(243,244,245,0.5)"
          >
            <img
              class="banner-img"
              v-if="formData.background_maps"
              :src="formData.background_maps"
              alt=""
            />
          </div>
        </el-form-item>

        <el-form-item label="圈子名称" prop="circle_name">
          <div class="community-title f-a-c">
            <el-input
              class="community-title"
              placeholder="请输入圈子名称"
              v-model="formData.circle_name"
              maxlength="40"
            >
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="圈子简介" prop="circle_introduce">
          <div class="community-content-box">
            <el-input
              type="textarea"
              class="community-content"
              :autosize="true"
              v-model="formData.circle_introduce"
              placeholder="请输入圈子简介"
              maxlength="500"
            >
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="圈子类型" prop="plate_id">
          <div
            class="community-type-box f-j-sb-a-c"
            :class="{ 'community-type-box-show': selectShow }"
            @click="selectShow = !selectShow"
            v-ClickOutside="() => (selectShow = false)"
          >
            <span :class="{ 'select-active': selectActive }">{{
              selectActive ? selectActive.plate_name : "请选择圈子类型"
            }}</span>
            <svg-icon
              :class="{ 'svg-icon-show': selectShow }"
              name="icon-jiantou-xia"
              class="svg-icon"
            ></svg-icon>
            <div
              class="community-select"
              :class="{
                'community-select-show': selectShow && selectList.length > 5,
              }"
              :style="{
                height: selectShow
                  ? selectList.length >= 5
                    ? '220px'
                    : selectList.length * 40 + 20 + 'px'
                  : '0px',
              }"
            >
              <div
                class="community-item f-a-c ellipsis"
                v-for="(item, index) in selectList"
                :key="index"
                @click="selectActive = item"
              >
                <span class="ellipsis">{{ item.plate_name }}</span>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div class="create-circle-text">
        请认真仔细阅读《圈主协议》，若所见圈子内涉及时政，色情，暴力，无资质荐股，推币等违法内容传播，官方将立即永久封停圈子和账号，请各用户自觉遵守国家法律和平台规则。
      </div>

      <template #footer right>
        <span class="dialog-footer f-j-sb-a-c">
          <el-checkbox v-model="isConsent" class="bottom-check"
            >我已阅读并同意《圈子协议》</el-checkbox
          >

          <div class="btn-box f-a-c">
            <div class="btn close-btn f-j-a-c" @click="close">取消</div>
            <el-button
              class="btn confirm-btn f-j-a-c"
              @click="confirm"
              :loading="sendLoading"
              >确定</el-button
            >
          </div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import ClickOutside from "element-plus/lib/directives/click-outside/index";
import { options, circle } from "@/axios/community.js";
import upload from "@/components/upload.vue";
import { toFixedNum } from "@/utils/common.js";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

import {
  defineComponent,
  reactive,
  toRefs,
  onUnmounted,
  onMounted,
  computed,
  watch,
  getCurrentInstance,
  ref,
} from "vue";
export default defineComponent({
  components: { upload },
  directives: { ClickOutside },
  props: {
    circleInfo: {
      type: Object,
      default: () => {},
    }, //修改圈子传入 圈子信息
  },
  setup(props, { attrs, slots, emit }) {
    const router = useRouter();
    const { proxy } = getCurrentInstance();
    const store = useStore();
    const formRef = ref(null); //表单

    let data = reactive({
      centerDialogVisible: false,
      formData: {
        head_portrait: "", //头像
        background_maps: "", //背景图
        circle_name: "", //圈子名称
        circle_introduce: "", //圈子简介
        plate_id: "", //圈子类型id
        id: "",
      },

      formRules: {
        head_portrait: [
          {
            required: true,
            message: "请上传圈子头像",
            trigger: "change",
          },
        ],

        background_maps: [
          {
            required: true,
            message: "请上传圈子背景图",
            trigger: "change",
          },
        ],

        circle_name: [
          {
            required: true,
            message: "请输入圈子名称",
            trigger: "change",
          },
        ],

        circle_introduce: [
          {
            required: true,
            message: "请输入圈子简介",
            trigger: "change",
          },
        ],

        plate_id: [
          {
            required: true,
            message: "请选择圈子分区",
            trigger: "change",
          },
        ],
      },

      selectList: [], //圈子类型下拉框
      selectActive: "", //下拉选中
      selectShow: false, //下拉框展开收齐
      avatarUploadLoading: false, //头像上传loading
      bannerUploadLoading: false, //背景图上传loading
      isConsent: false, //是否同意

      sendLoading: false, //发送loading
    });

    // 监听选中 赋值到表单
    watch(
      () => data.selectActive,
      (newVal, oldVal) => {
        if (newVal) {
          data.formData.plate_id = newVal.id;
        } else {
          data.formData.plate_id = "";
        }
      }
    );

    // 监听弹框打开 获取圈子分区
    watch(
      () => data.centerDialogVisible,
      (newVal, oldVal) => {
        if (newVal) {
          getoptions();
        }
      }
    );

    // 圈子分区
    let getoptions = () => {
      options().then((res) => {
        data.selectList = res.data;
        proxy.$nextTick(() => {
          if (JSON.stringify(props.circleInfo) != "{}") {
            data.selectActive = data.selectList.filter(
              (item) => item.id == data.formData.plate_id
            )[0];
          }
        });
      });
    };

    // 打开弹框
    let open = () => {
      data.centerDialogVisible = true;
      proxy.$nextTick(() => {
        if (props.circleInfo && JSON.stringify(props.circleInfo) != "{}") {
          for (let key in data.formData) {
            data.formData[key] = props.circleInfo[key];
          }
        }
      });
    };

    // 取消
    let close = () => {
      data.centerDialogVisible = false;
      formResetFields();
      data.selectActive = "";
    };

    // 确定
    let confirm = () => {
      formRef.value.validate((valid, fields) => {
        if (valid) {
          if (!data.isConsent) return ElMessage.warning("请阅读并同意圈子协议");
          data.sendLoading = true;
          circle({ ...data.formData })
            .then((res) => {
              data.sendLoading = false;

              ElMessage.success("提交成功，将会在24小时之内处理");
              close();
            })
            .catch((err) => {
              data.sendLoading = false;

              ElMessage.error(err.message);
            });
        } else {
          data.sendLoading = false;

          console.log("error submit!", fields);
        }
      });
    };

    // 头像上传成功
    let avatarUploadSucess = (obj) => {
      data.formData.head_portrait = obj.url;
      data.avatarUploadLoading = false;
    };

    // 头像上传前
    let avatarUploadFileQueued = (file) => {
      data.avatarUploadLoading = true;
    };

    //
    // 背景图上传成功
    let bannerUploadSucess = (obj) => {
      data.formData.background_maps = obj.url;
      data.bannerUploadLoading = false;
    };

    // 头像上传前
    let bannerUploadFileQueued = (file) => {
      data.bannerUploadLoading = true;
    };

    // 清空表单
    let formResetFields = () => {
      formRef.value.resetFields();
    };

    return {
      formRef,
      getoptions,
      bannerUploadSucess,
      bannerUploadFileQueued,
      avatarUploadSucess,
      avatarUploadFileQueued,
      close,
      confirm,
      open,
      ...toRefs(data),
    };
  },
});
</script>
<style lang="scss" scoped>
.upload-body {
  :deep(.el-dialog.el-dialog--center) {
    border-radius: 20px;
    min-width: 520px;
    max-width: 600px;
  }

  :deep(.el-dialog--center .el-dialog__footer) {
    text-align: right !important;
  }
}

// 表单
.form-box {
  :deep(.el-form-item__label) {
    font-size: 14px;
    font-weight: bold;
    color: #000000;
  }
  > .el-form-item:not(:first-child) {
    padding-top: 20px;
  }
}

// 圈子头像上传
.avatar-upload-box {
  border: 1px solid #ececec;
  width: 136px;
  height: 136px;
  border-radius: 10px;
  font-size: 12px;
  line-height: 20px;
  color: #64c8dc;

  .upload-icon {
    width: 24px;
    height: 24px;
    margin-bottom: 2px;
  }

  .upload-title{
    padding-top: 6px;
    font-size: 12px;
    color: #656f79;
  }
}

.avatar-img {
  width: 136px;
  height: 136px;
  border-radius: 10px;
  object-fit: cover;
  display: block;
}

.avatar-upload-loading {
  width: 136px;
  height: 136px;
  border-radius: 10px;
  overflow: hidden;
  background-size: cover;
  position: relative;
  > img {
    position: absolute;
  }
}

// 圈子背景图
.banner-upload-box {
  width: 100%;
  height: 120px;
}
.banner-img {
  width: 100%;
  height: 120px;
  border-radius: 10px;
  object-fit: cover;
  display: block;
}
.banner-upload-loading {
  width: 100%;
  height: 120px;
}

// 圈子名称
.community-title {
  height: 40px;
  width: 100%;
  border-radius: 10px;
  :deep(.el-input__wrapper) {
    border-radius: 10px;
    background: transparent;
  }
  :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #64c8dc inset;
  }
}

// 圈子类型
.community-type-box {
  height: 40px;
  border-radius: 10px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  width: 100%;
  cursor: pointer;
  padding: 0 20px 0 10px;
  position: relative;
  color: #a8abb2;

  .svg-icon {
    width: 20px;
    height: 20px;
    transition: all 0.2s;
  }
  .svg-icon-show {
    transform: rotate(180deg);
  }
  .select-active {
    color: #000000;
  }

  //   /下拉选
  .community-select {
    position: absolute;
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    top: 45px;
    width: 100%;
    left: 0;
    background: #ffffff;
    max-height: 220px;
    z-index: 20;
    overflow: hidden;
    transition: all 0.2s;
    > div:first-child {
      margin-top: 10px;
    }
    > div:last-child {
      margin-bottom: 10px;
    }
    .community-item {
      height: 40px;
      padding: 0 10px;
      font-size: 14px;
      color: #000000;
      &:hover {
        color: #64c8dc;
        background: rgba(100, 200, 220, 0.1);
      }
    }
  }
  .community-select-show {
    overflow-y: auto;
  }
}
.community-type-box-show {
  box-shadow: 0 0 0 1px #64c8dc inset !important;
}

// 简介
.community-content-box {
  position: relative;
  width: 100%;
}
.community-content {
  min-height: 90px;

  :deep(.el-textarea__inner) {
    border-radius: 10px;
    min-height: 90px !important;
    max-height: 200px;
    font-size: 14px;
    resize: none;
    &:focus {
      box-shadow: 0 0 0 1px #64c8dc inset !important;
    }
  }
}

// 底部说明
.create-circle-text {
  font-size: 12px;
  color: #656f79;
  line-height: 20px;
}

// 底部按钮
.dialog-footer {
  .bottom-check {
    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: #64c8dc;
      border-color: #64c8dc;
    }
    :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
      color: #64c8dc;
    }
    :deep(.el-checkbox__label) {
      color: #656f79;
      font-size: 12px;
      font-weight: 400;
    }
  }

  .btn-box {
    font-size: 14px;
    font-weight: bold;
    justify-content: flex-end;
    > .btn {
      height: 36px;
      width: 80px;
      border-radius: 10px;
      margin-left: 10px;
      cursor: pointer;
      background: #f3f4f5;
      color: #656f79;
      &:active {
        opacity: 0.7;
      }
    }
    .confirm-btn {
      background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
      color: #ffffff;
      border: none;
    }
  }
}
</style>
